package param

import (
	"math/rand"
	"strconv"
	"log"
)

type UserAgent struct {
	Name string `json:"name"`
	UserAgent string `json:"userAgent"`
	Weight string `json:"weight"`
	MinValue int
	MaxValue int
}

type UserAgentParam struct {
	UserAgents []UserAgent `json:"userAgents"`
	maxRandomWeight int
}

func (this *UserAgentParam) GetRandomUserAgent() string {
	randomWeight := rand.Intn(this.GetMaxRandomWeight())
	for _,value:=range this.UserAgents{
		if randomWeight>=value.MinValue&&randomWeight<value.MaxValue{
			return value.UserAgent
		}
	}
	return this.UserAgents[0].UserAgent
}

func (this *UserAgentParam)init(){
	lastValue:=0
	for _,value:=range this.UserAgents{
		weightInt,err:=strconv.Atoi(value.Weight)
		if err!=nil{
			log.Printf("%s weight err:%v",value.Name,err)
			value.MinValue=0
			value.MaxValue=0
		}else{
			value.MinValue=lastValue
			lastValue+=weightInt
			value.MaxValue=lastValue
		}
	}
	this.maxRandomWeight=lastValue
}

func (this *UserAgentParam) GetMaxRandomWeight() int {
	return this.maxRandomWeight
}

